//
//  WaitTakingViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/9/6.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "WaitTakingViewController.h"
#import "BatchReceiveViewController.h"
#import "ExpressDetailViewController.h"
#import "SingleScanViewController.h"
#import "SocketRequest.h"
#import "Singleton.h"
#import "WaitTakingGroup.h"
#import "WaitTakingCell.h"
#import "TSHeader.h"

@interface WaitTakingViewController ()<SocketRequestDelegate,SingleScanViewControllerDelegate,ExpressDetailViewControllerDelegate,BatchReceiveViewControllerDelegate> {
    SocketRequest *_socketRequest;
    int _positionPage;
    NSMutableArray *_expressGroupList;
    BOOL _isFirst;
}

@end

@implementation WaitTakingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"待取件";
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
        _positionPage = 1;
        _expressGroupList = [NSMutableArray arrayWithCapacity:1];
        _isFirst = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _customSearch = [[CustomSearchView alloc] initWithFrame:CGRectMake(0, 0, 320, 45)];
    _customSearch.delegate = self;
    self.tableView.tableHeaderView = _customSearch;
    [self.tableView setContentOffset:CGPointMake(0, 45) animated:YES];
    if ([Singleton shareInstance].userMessage.websiteIsSend) {
        [self rightBarButtonItemTitle:@"批量签收" Method:@selector(batchReceveExpressVC)];
    }
    [self getWaitTakingExpressFromSqlit];
    [self handelNetWorkMethod];
}

- (void)batchReceveExpressVC {
    [MobClick event:@"daiqujian_link_piliangqianshou"];
    BatchReceiveViewController *batchRVC = [[BatchReceiveViewController alloc] initWithNibName:@"BatchReceiveViewController" bundle:nil];
    batchRVC.delegate = self;
    [self.navigationController pushViewController:batchRVC animated:YES];
}

- (void)getWaitTakingExpressFromSqlit {
    [_expressGroupList removeAllObjects];
    NSString *sql = [NSString stringWithFormat:@"ORDER BY receiveTime DESC"];
    NSArray *array = [WaitTakingExpress findByCriteria:sql];
    for (WaitTakingExpress *express in array) {
        WaitTakingGroup *group = [_expressGroupList lastObject];
        if ([group.showDay isEqualToString:express.showDay]) {
            [group.expressList addObject:express];
        } else {
            WaitTakingGroup *anotherGroup = [[WaitTakingGroup alloc] initWithWaitTakingExpress:express];
            [anotherGroup.expressList addObject:express];
            [_expressGroupList addObject:anotherGroup];
        }
    }
    [self reloadTableViewWithLoaded:YES];
    if (_expressGroupList.count > 0) {
        [ToastActivity makeActivity:@"正在加载中..." InView:self.view];
    }
    [self getWaitTakingExpressSocket];
}

//获取待取件
- (void)getWaitTakingExpressSocket {
    if (_expressGroupList.count <= 0) {
        [self.tableView makeLoading];
    } else {
        self.tableView.backgroundView = nil;
    }
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STR9"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:_customSearch.searchTextField.text] length:64];
    NSString *positionString = [NSString stringWithFormat:@"%d",_positionPage];
    [mutableData appendBytes:[SocketMethod checkLegal:positionString] length:16];
    [mutableData appendBytes:[@"10" UTF8String] length:16];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

- (void)reloadTableViewWithLoaded:(BOOL)isLoaded {
    self.tableView.isShowFooterView = !isLoaded;
    if (_expressGroupList.count <= 0) {
        if (_customSearch.searchTextField.text.length <= 0) {
            [self.tableView makeTip:@"查无结果。请重新搜索！"];
        } else {
            [self.tableView makeTip:@"无待取件"];
        }
    } else {
        [self.tableView makeNone];
    }
    [self.tableView reloadData];
    if (_isFirst) {
        _isFirst = NO;
        _tableView.contentOffset = CGPointMake(0, 45);
    }
}

#pragma mark BatchReceiveViewControllerDelegate 
- (void)receiveExpressSuccess {
    _positionPage = 1;
    [self getWaitTakingExpressSocket];
}

#pragma mark CustomSearchViewDelegate
- (void)cancelSearch {
    _customSearch.isShowCancel = NO;
    _customSearch.searchTextField.text = @"";
    _positionPage = 1;
    [self getWaitTakingExpressSocket];
}

- (void)startScanning {
    SingleScanViewController *scanVC = [[SingleScanViewController alloc] initWithNibName:@"SingleScanViewController" bundle:nil];
    scanVC.delegate = self;
    [self.navigationController pushViewController:scanVC animated:YES];
}

- (void)startSearchText:(NSString *)text {
    _customSearch.isShowCancel = NO;
    _positionPage = 1;
    [self getWaitTakingExpressSocket];
}

#pragma mark SingleScanViewControllerDelegate
- (void)didFinishSingleScanningCode:(NSString *)code {
    _positionPage = 1;
    _customSearch.searchTextField.text = code;
    [self getWaitTakingExpressSocket];
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _expressGroupList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    WaitTakingGroup *group = [_expressGroupList objectAtIndex:section];
    return group.expressList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 22;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 22)];
    headerView.backgroundColor = UIColorFromRGB(0xebebeb);
    WaitTakingGroup *group = [_expressGroupList objectAtIndex:section];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(12, 1, 150, 20)];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:11];
    label.textColor = TipTextColor;
    label.text = [NSString stringWithFormat:@"%@(%d)",group.showDay,group.dayCount];
    [headerView addSubview:label];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    WaitTakingGroup *group = [_expressGroupList objectAtIndex:indexPath.section];
    if (indexPath.row == (group.expressList.count - 1)) {
        return 200;
    }
    return 206;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIndentifier = @"WaitTakingCell";
    WaitTakingCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"WaitTakingCell" owner:self options:nil] lastObject];
    }
    WaitTakingGroup *group = [_expressGroupList objectAtIndex:indexPath.section];
    WaitTakingExpress *express = [group.expressList objectAtIndex:indexPath.row];
    [cell reloadWaitTakingCell:express];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    WaitTakingGroup *group = [_expressGroupList objectAtIndex:indexPath.section];
    WaitTakingExpress *express = [group.expressList objectAtIndex:indexPath.row];
    ExpressDetailViewController *expressDVC = [[ExpressDetailViewController alloc] initWithNibName:@"ExpressDetailViewController" bundle:nil];
    expressDVC.inwayExpressId = express.inwayExpressId;
    expressDVC.delegate = self;
    expressDVC.indexPath = indexPath;
    [self.navigationController pushViewController:expressDVC animated:YES];
}

#pragma mark ExpressDetailViewControllerDelegate
- (void)smsSendSuccess:(NSIndexPath *)indexPath {
    WaitTakingGroup *group = [_expressGroupList objectAtIndex:indexPath.section];
    WaitTakingExpress *express = [group.expressList objectAtIndex:indexPath.row];
    express.smsSendType = 0;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)takeExpressSuccess:(NSIndexPath *)indexPath {
    WaitTakingGroup *group = [_expressGroupList objectAtIndex:indexPath.section];
    WaitTakingExpress *express = [group.expressList objectAtIndex:indexPath.row];
    [group.expressList removeObject:express];
    [express deleteObject];
    group.dayCount --;
    if (group.dayCount == 0) {
        [_expressGroupList removeObject:group];
        [self.tableView reloadData];
    } else {
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (void)updateExpress:(NSIndexPath *)indexPath Telephone:(NSString *)telephone Address:(NSString *)address {
    WaitTakingGroup *group = [_expressGroupList objectAtIndex:indexPath.section];
    WaitTakingExpress *express = [group.expressList objectAtIndex:indexPath.row];
    express.telephone = telephone;
    express.address = address;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.tableView pullScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self.tableView pullscrollViewDidEndDragging:scrollView];
}

#pragma mark PullTableViewDelegate
- (void)startRefreshHeaderView {
    _positionPage = 1;
    [self getWaitTakingExpressSocket];
}

- (void)startRefreshFooterView {
    _positionPage += 10;
    [self getWaitTakingExpressSocket];
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    [ToastActivity dismissInView:self.view];
    [self.tableView endRefreshPullTableView];
    if ([code isEqualToString:SuccessSocket]) {
        if (_positionPage == 1) {
            [_expressGroupList removeAllObjects];
            [WaitTakingExpress clearTable];
        }
        int count = [[SocketMethod stringSubdata:data Range:NSMakeRange(0, 16)] intValue];
        if (count > 0) {
            self.title = [NSString stringWithFormat:@"待取件(%d)",count];
        } else {
            self.title = @"待取件";
        }
        NSString *content = [SocketMethod stringDecryHexData:data Range:NSMakeRange(16, data.length - 16)];
        NSArray *array = [content componentsSeparatedByString:@"|"];
        int i = 0;
        for (NSString *string in array) {
            if (string.length > 0) {
                WaitTakingExpress *express = [[WaitTakingExpress alloc] initWithString:string];
                [express saveOrUpdate];
                WaitTakingGroup *group = [_expressGroupList lastObject];
                if ([group.showDay isEqualToString:express.showDay]) {
                    [group.expressList addObject:express];
                } else {
                    WaitTakingGroup *anotherGroup = [[WaitTakingGroup alloc] initWithWaitTakingExpress:express];
                    [anotherGroup.expressList addObject:express];
                    [_expressGroupList addObject:anotherGroup];
                }
                i ++;
            }
        }
        [self reloadTableViewWithLoaded:((i < 10) ? YES : NO)];
    } else {
        if (_expressGroupList.count <= 0) {
            [self.tableView makeTip:msg];
        } else {
            [DSToast showText:msg InView:self.view];
        }
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    [self.tableView endRefreshPullTableView];
    [ToastActivity dismissInView:self.view];
    self.tableView.isShowFooterView = NO;
    if (_expressGroupList.count <= 0) {
        [self.tableView makeTip:msg Title:@"重新加载" Target:self Selector:@selector(getWaitTakingExpressSocket)];
    }
    [DSToast showText:msg InView:self.view];
}

- (void)dealloc {
    _socketRequest = nil;
    _expressGroupList = nil;
}

@end
